<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>采购入库</title>
<script type="text/javascript" src="../static/easyui/jquery.min.js"></script>
<script type="text/javascript" src="../static/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../static/easyui/locale/easyui-lang-zh_CN.js"></script>
<link rel="stylesheet" href="../static/easyui/themes/icon.css">
<link rel="stylesheet" href="../static/easyui/themes/metro-red/easyui.css">
</head>
<body>
<script type="text/javascript">
//时间转换 
function comformatDate(date) {
	var day = new Date(date); 
	var Year = 0; 
	var Month = 0; 
	var Day = 0; 
	var CurrentDate = ""; 
	//初始化时间 
	Year= day.getFullYear();//
	Month= day.getMonth()+1; 
	Day = day.getDate(); 
	Hour = day.getHours(); 
	 Minute = day.getMinutes(); 
	 Second = day.getSeconds(); 
	CurrentDate += Year + "-"; 
	if (Month >= 10 ) { 
		CurrentDate += Month + "-"; 
	}else { 
		CurrentDate += "0" + Month + "-"; 
	} 
	if (Day >= 10 ) { 
		CurrentDate += Day ; 
	}else { 
		CurrentDate += "0" + Day ; 
	} 
	if(Hour>=10){
		CurrentDate +=" "+Hour;
	}else{
		CurrentDate +=" "+"0"+Hour;
	}
	if(Minute>=10){
		CurrentDate +=":"+Minute;
	}else{
		CurrentDate +=":"+"0"+Minute;
	}
	if(Second>=10){
		CurrentDate +=":"+Second;
	}else{
		CurrentDate +=":"+"0"+Second;
	}
	return CurrentDate; 
};

//添加药品
$("#drug-list").datagrid({
	 onDblClickRow:function(rowIndex,rowDate){
		 var zhongyao=$("#dept-add-dg").datagrid("getRows");//得到药品表格的所有行
		 if(zhongyao.length==0){//如果他的长度为零,就表示没有一条数据就新增一条
			 rowDate.purchase_total_number=1;//设置一个药品数量默认值
			 $('#dept-add-dg').datagrid('appendRow',rowDate);
				var ypdj=rowDate.drug_selling_price;//得到选中药品的金额
				var ypdjs=parseInt(ypdj); 
				var dqz=$("#purchase_amount_of_cg").val();//得到当前的总金额
				var dqzs=parseInt(dqz);
				$("#purchase_amount_of_cg").textbox("setValue",ypdjs+dqzs);//重新赋值给药品总金额
		 }else{
			 var a;//ar一个变量作为得到具体哪一行的参数
			 var opin = true;
			 for (var i= 0;i<zhongyao.length;i++){				 
					 if(rowDate.drug_id==zhongyao[i].drug_id){
						 opin = false;
						 a=i;
					 }
				}
			 if(opin){//如果判断表格里面没有相同的药品就新增一行
				 rowDate.purchase_total_number=1;
				 $('#dept-add-dg').datagrid('appendRow',rowDate);
				 	var ypdj=rowDate.drug_selling_price;//得到选中药品的金额
				 	var ypdjs=parseInt(ypdj); 
					var dqz=$("#purchase_amount_of_cg").val();//得到当前的总金额
					var dqzs=parseInt(dqz);
					$("#purchase_amount_of_cg").textbox("setValue",ypdjs+dqzs);//重新赋值给药品总金额				 
			 }else{//判断表格里面有相同的药品就数量加一
				 rowDate.purchase_total_number=parseInt(rowDate.purchase_total_number)+parseInt(1);
				 $('#dept-add-dg').datagrid('updateRow',{index:a,row:{rowDate}});
			 }
			 var sum = 0;//定义一个值来存储金额
			 for (var i = 0; i<zhongyao.length; i++) {//循环右边药单所有行取出药品数量和单价相乘
				var row = zhongyao[i];
				sum = sum + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);
			 } 
			 $("#purchase_amount_of_cg").textbox("setValue",sum);//重新赋值给药品总金额
			 
		 }		 
	 }
	 
});

		//选择药品展示列表
		$(function(){		
			//新增显示选择药品界面
			$("#rukuxuanze").click(function(){
				$("#xuanze").window("open");
			});	
			//关闭详情界面
			$("#queding").click(function(){
				   $("#rukuxiangqing").window("close");
			}); 
			
			//采购单表格
			$('#caigoudan').datagrid({
				url:'rukubg',
			    pagination:true,
			    pageNumber:1,
			    pageSize:7,
			    pageList:[7,14],
			    columns:[[			    	
			    	{field:'',checkbox:true,width:"130px",align:'center'},
					{field:'purchaseId',title:'采购编号',width:"130px",align:'center'},
					{field:'purchaseTime',title:'采购时间',width:"170px",align:'center',formatter:comformatDate},
					{field:'purchasePeople',title:'采购人',width:"130px",align:'center'},
					{field:'purchaseAmountOfCg',title:'采购总金额',width:"130px",align:'center'},
					{field:'purchaseTotalNumber',title:'总数量',width:"130px",align:'center'},
					{field:'purchaseBatchNumberCg',title:'采购批号',width:"130px",align:'center'},
					{field:'purchaseStatic',title:'状态',width:"130px",align:'center'},
					{field:'caozuo',title:'操作',width:140,align:'center',
						formatter:function(value,row,index){
							return "<input type='button' style='background:#E4F1FB;color:#2779AA;border:none' onclick='chakan("+row.purchaseId+")' value='查看详情'/>";
						}	
					}
				]]			
			});	
			
			//选择药品表格
			$('#drug-list').datagrid({
				url:'yaopinxinxi',
				pagination:true,
			    pageNumber:1,
			    pageSize:5,
			    pageList:[5,10],
				columns:[[
					{field:'drug_name',title:'药品名称',width:"150px",align:'center'},
					{field:'drug_specifications',title:'药品规格',width:"150px",align:'center'},
					{field:'drug_selling_price',title:'销售价',width:"150px",align:'center'},
					{field:'drug_types_name',title:'药品类型',width:"150px",align:'center'},
					{field:'factory_name',title:'供应商',width:"150px",align:'center'}
				]]
			});			
		});
		
		//点击保存按钮
		$("#baocun").click(function(){
			$("<form method='post'>").appendTo("body").form({
				url:'save-order',
				onSubmit:function(param){
					//采购批号
					param["caigou.purchaseBatchNumberCg"] = $("#purchase_batch_number_cg").val();
					//采购时间
					//param["caigou.purchaseTime"] = new Date();
					//采购人
					param["caigou.purchasePeople"] = $("#purchase_people").val();
					//采购总金额
					param["caigou.purchaseAmountOfCg"] = $("#purchase_amount_of_cg").val();
					var sum=0;
					//获取表格中的采购的详情记录
					var rows = $("#dept-add-dg").datagrid("getRows");
					//console.log(rows);
					for (var i = 0; i < rows.length; i++) {															
						//药品编号
						param["caigoudetails["+i+"].DrugsYk.DrugId"] = rows[i]["drug_id"];
						//采购数量
						param["caigoudetails["+i+"].xiangqingDrugNumber"] = rows[i]["purchase_total_number"];
						//采购价格
						param["caigoudetails["+i+"].drugSellingPrice"] = rows[i]["drug_selling_price"];
						var row=rows[i];
						sum=sum+parseInt(row.purchase_total_number);			
					} 
					//入库数量				
					param["caigou.purchaseTotalNumber"] =sum;
					//alert("数量"+sum);
				},
				success:function(d){
					$("#caigoudan").datagrid("reload");//刷新
					$.messager.show({
							title:'提 示',
							msg:'入库新增成功！！！！',
							height:200,
							timeout:1000,
							showType:'slide'
					});
					//采购批号
					$("#purchase_batch_number_cg").textbox('setValue',null);
					//采购时间
					$("#purchase_time").textbox('setValue',null);
					//总金额
					$("#purchase_amount_of_cg").textbox('setValue',null);
					//采购人
					$("#purchase_people").textbox('setValue',null);
					//alert(d);
				}
			}).submit();
		});	
		
	//查看详情
	function chakan(id2){
		$("#caigouxiangqingjiemian").window("open");//打开采购详情界面
		var row=$('#caigoudan').datagrid('getSelected');
		var id2 = row["purchaseId"];//id
		//alert(id2);
		$("#tongguoshenhe").val(id2); 
		//审核详情表格
		$('#caigouxiangqing').datagrid({
		    url:'caigxq',
		    queryParams: {
		    	purchase_id:id2
		    },
		    columns:[[
		    	{field:'',checkbox:true,width:"130px",align:'center'},
		    	{field:'details_id',title:'采购详情编号',width:"130px",align:'center'},
		    	{field:'purchase_id',title:'采购编号',width:"130px",align:'center'},
				{field:'drug_id',title:'药品编号',width:"130px",align:'center'},
				{field:'drug_pc',title:'生产批次',width:"130px",align:'center',editor:'numberspinner'},
				{field:'xiangqing_drug_number',title:'数量',width:"130px",align:'center',editor:'numberspinner'},
				{field:'drug_name',title:'药品名称',width:"130px",align:'center'}
		    ]],
		    pagination:true,
		    pageNumber:1,
		    pageSize:5,
		    pageList:[5,10,15]
		});	
	}
	
	
	//进行审核----库存
	 $("#tongguoshennhe").click(function(){
		//修改状态
			var aa=$('#tongguoshenhe').val();
			$.ajax({
				url:'shtg',
				type:'post',
				data:{
					'purchaseId':aa,
				},
				success:function(d){
					if(parseInt(d)==1){
						$("#caigoudan").datagrid("reload");
						$.messager.show({
							title:'提 示',
							msg:'入库成功！！！！',
							height:200,
							timeout:1000,
							showType:'slide'
						});
					}else{
						alert("审核失败");
					}
				}
			})
			$("#caigouxiangqingjiemian").window("close");
			
			
			//根据批次改库存数量
			 $("<form method='post'>").appendTo("body").form({
					url:'xinpici',
					onSubmit:function(param){
						//获取表格中的采购的详情记录
						var rows = $("#caigouxiangqing").datagrid("getRows");
						//console.log(rows);
						for (var i = 0; i < rows.length; i++) {
							//药品编号
							param["inven["+i+"].DrugsYk.DrugId"] = rows[i]["drug_id"];
							//药品数量
							param["inven["+i+"].inventoryNumber"] = rows[i]["xiangqing_drug_number"];
							//药品批次
							param["inven["+i+"].drugPc"] = rows[i]["drug_pc"];
						}
					},
					success:function(d){
						//alert(d);
					}
				}).submit();
	 });
	 
	//生产批次点击---修改批次
	$.extend($.fn.datagrid.methods, {
		editCell: function(jq,param){
			return jq.each(function(){
				var opts = $(this).datagrid('options');
				var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
				for(var i=0; i<fields.length; i++){
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor1 = col.editor;
					if (fields[i] != param.field){
						col.editor = null;
					}
				}
				$(this).datagrid('beginEdit', param.index);
				for(var i=0; i<fields.length; i++){
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor = col.editor1;
				}
			});
		}
	});
	var editIndex = undefined;
	function endEditing(){
		if (editIndex == undefined){return true}
		if ($('#caigouxiangqing').datagrid('validateRow', editIndex)){
			$('#caigouxiangqing').datagrid('endEdit', editIndex);
			editIndex = undefined;
			return true;
		} else {
			return false;
		}
	}
	function onClickCell(index, field){ //下面表格里要有这个点击
		if (endEditing()){
			$('#caigouxiangqing').datagrid('selectRow', index)
					.datagrid('editCell', {index:index,field:field});
			editIndex = index;
		}
	}
		  
		    //表格中的文本框
			function formatAction(value,row,index){
				 if (row.editing){
						var s = '<input type="button" style="background:#E4F1FB;color:#2779AA;border:none" onclick="saverow('+index+')" value="保存"/> ';
						var c = '<input type="button" style="background:#E4F1FB;color:#2779AA;border:none" onclick="cancelrow(this)" value="返回"/> ';
						return s+c;
					} else {
						var e = '<input type="button" style="background:#E4F1FB;color:#2779AA;border:none" onclick="editrow(this)" value="编辑"/> ';
						var d = '<input type="button" style="background:#E4F1FB;color:#2779AA;border:none" onclick="deleterow(this)" value="删除"/> ';
						return e+d;
					} 
			}			
			$.extend($.fn.datagrid.defaults.editors, {
				numberspinner: {
					init: function(container, options){
						var input = $('<input type="text">').appendTo(container);
						return input.numberspinner(options);
					},
					destroy: function(target){
						$(target).numberspinner('destroy');
					},
					getValue: function(target){
						return $(target).numberspinner('getValue');
					},
					setValue: function(target, value){
						$(target).numberspinner('setValue',value);
					},
					resize: function(target, width){
						$(target).numberspinner('resize',width);
					}
				}
			});
			$(function(){
				$('#dept-add-dg').datagrid({
					onBeforeEdit:function(index,row){
						$(this).datagrid('updateRow', {index:index,row:{editing:true}})
					},
					onAfterEdit:function(index,row){
						$(this).datagrid('updateRow', {index:index,row:{editing:false}})
					},
					onCancelEdit:function(index,row){
						$(this).datagrid('updateRow', {index:index,row:{editing:false}})
					}
				});
			});
			function getRowIndex(target){
				var tr = $(target).closest('tr.datagrid-row');
				return parseInt(tr.attr('datagrid-row-index'));
			}
			function editrow(target){
				$('#dept-add-dg').datagrid('beginEdit', getRowIndex(target));
			}
			//删除事件
			function deleterow(target){
				$.messager.confirm('温馨提示','确定删除?',function(r){
					if (r){
						$('#dept-add-dg').datagrid('deleteRow', getRowIndex(target));
						var rows = $('#dept-add-dg').datagrid("getRows");
						
						var bb = 0;
						for (var i = 0; i < rows.length; i++) {
							var row =rows[i];
							bb = bb + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);
						}
						$("#purchase_amount_of_cg").textbox('setValue',bb);
					}
				});
			}
			//保存事件
			function saverow(target){
				var rows = $('#dept-add-dg').datagrid("getRows");
				$('#dept-add-dg').datagrid('endEdit', target);
			
				var bb = 0;
				for (var i = 0; i < rows.length; i++) {
					if(rows[i]["purchase_total_number"]<=0){
						rows[i]["purchase_total_number"]=1;
						$('#dept-add-dg').datagrid('refreshRow',i);
						 for (var i = 0; i < rows.length; i++) {
							 var row = rows[i];
							sum = sum + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);
						}
						 $("#purchase_amount_of_cg").textbox('setValue',sum);//重新赋值给药品总金 
						 break;
					}else if(rows[i]["purchase_total_number"]==''){
						rows[i]["purchase_total_number"]=1;
						$('#dept-add-dg').datagrid('refreshRow',i);
						 for (var i = 0; i < rows.length; i++) {
							 var row = rows[i];
							sum = sum + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);
						}
						 $("#purchase_amount_of_cg").textbox('setValue',sum);//重新赋值给药品总金 
						 break;
					}else if(!(/^[1-9]\d*$/).test(rows[i]["purchase_total_number"])){
						
						rows[i]["purchase_total_number"]=1;
						$('#dept-add-dg').datagrid('refreshRow',i);
					 for (var i = 0; i < rows.length; i++) {
						 var row = rows[i];
						sum = sum + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);
						}
					 $("#purchase_amount_of_cg").textbox('setValue',sum);//重新赋值给药品总金 
					 break;
					}else{
						var row =rows[i];
						bb = bb + parseInt(row.drug_selling_price)*parseInt(row.purchase_total_number);	
					}
				}
				$("#purchase_amount_of_cg").textbox('setValue',bb);
			}
			
			function cancelrow(target){
				$('#dept-add-dg').datagrid('cancelEdit', getRowIndex(target));
			}				
			
			//文本框回车事件搜索
			$('#exchangeSear').searchbox({
				searcher:function(value,name){
					$('#caigoudan').datagrid({
						url:'rukubg?purchase_id='+value,	
					});				  
				}
			});
</script>	
<!-- =======隐藏域======= -->
<input type="hidden" type="text" id="tongguoshenhe">

		<!-- 第一个选项卡 -->	    
		<div>
			 <div class="easyui-layout" style="padding:20px;">
			 	<input id="purchase_batch_number_cg" value="${shijian}" class="easyui-textbox" data-options="label:'采购批号：',width:260,labelAlign:'right'">
			 	<!-- <input id="purchase_time" class="easyui-datebox" data-options="label:'采购时间：',width:260,labelAlign:'right'"> -->			 	
			 	<input id="purchase_amount_of_cg" class="easyui-textbox" readonly data-options="label:'总金额：',value:0,width:260,labelAlign:'right'">	
			 	<input id="purchase_people" value="${user.userName}" class="easyui-textbox" data-options="label:'采购人：',width:260,labelAlign:'right'" style="border-top:none;">		 	
			 </div>
			 <div style="text-align:center;">
			 	<a id="rukuxuanze" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加药品</a>
				<a id="baocun" class="easyui-linkbutton" data-options="iconCls:'icon-ok',plain:true">保存</a>
		 	 </div>
			 <div style="height:200px;">
				<table id="dept-add-dg" class="easyui-datagrid" data-options="fit:true,fitColumns:true">    	
			    	<thead>   
					   <tr>   
					   	  <th data-options="field:'drug_id',width:100">药品编号</th>   
						  <th data-options="field:'drug_name',width:100">药品名称</th>   
						  <th data-options="field:'drug_selling_price',width:100">药品价格</th>   
						  <th data-options="field:'drug_specifications',width:100">规格</th>   
						  <th data-options="field:'purchase_total_number',width:100,"editor="{type:'numberspinner',options:{min:1}}">购买数量</th>
					   	  <th data-options="field:'caozuo',width:100,formatter:formatAction">操作</th>
					   </tr>   
					</thead>
				</table>
			</div>
			<div style="padding-top:10px;">
				<input id="exchangeSear" class="easyui-searchbox" style="width:280px;height:30px;"
						data-options="label:'采购编号：',prompt:'请输入采购编号',labelAlign:'right'">				
			</div>
			<!-- 采购单表格 -->
			<div style="height:200px;padding-top:10px;">		
				<table id="caigoudan" class="easyui-datagrid" data-options="fitColumns:true" style="padding:15px;height:300px;"></table> 
			</div>
		</div>
	
		<!-- 选择药品界面 -->
		<div id="xuanze" class="easyui-window" title="选择药品" style="width:800px;height:380px" data-options="iconCls:'icon-add',closed:true">   	 		
	 		<table id="drug-list" class="easyui-datagrid" data-options="fitColumns:true" style="padding:15px;height:340px;"></table>	 		
		</div>
		
		<!-- 采购详情界面 -->
		<div id="caigouxiangqingjiemian" class="easyui-window" title="采购详情" style="width:837px;height:450px" data-options="iconCls:'icon-add',closed:true">  
	 		<table id="caigouxiangqing" class="easyui-datagrid" data-options="fitColumns:true,onClickCell:onClickCell" style="padding:15px;height:350px;"></table>			
	 		<a id="tongguoshennhe" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" style="margin-left:630px;margin-top:20px;">确认入库</a> 
		</div>		
</body>
</html>
